package org.example;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从请求中获取用户名和密码
        String username = new String(request.getParameter("username").getBytes("ISO-8859-1"), "UTF-8");
        String email = request.getParameter("email");

        if (validateLogin(username, email)) {
            // 登录成功逻辑
            request.getSession().setAttribute("username", username);
            response.sendRedirect("index.jsp"); // 重定向到欢迎页面
        } else {
            // 登录失败逻辑
            request.setAttribute("errorMessage", "Invalid username or email");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    private boolean validateLogin(String username, String email) {
        // SQL查询语句，查找匹配的用户名和密码
        String sql = "SELECT COUNT(*) FROM users WHERE username = ? AND email = ?";

        try (Connection conn = DBUtil.getConn();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            // 设置查询参数
            ps.setString(1, username);
            ps.setString(2, email);

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    // 检查查询结果，如果存在匹配项，则返回true
                    return rs.getInt(1) > 0;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 出现异常时，考虑记录日志或其他错误处理逻辑
        }
        // 默认返回false
        return false;
    }
}
